import 'dart:convert';

import 'package:flutter_des/flutter_des.dart';

import '../public.dart';

class ReaderService {
  static Future<Article> fetchArticle(
      {String bookId, String catalogId, String num, bool forceServer}) async {
    var _bookId = "&bookId=" + bookId;
    var _catalogId = "&catalogId=" + catalogId;
    var _num = "&num=" + num;
    var _forceServer = forceServer == true ? "&force=1" : "";
    var param = await FlutterDes.encryptToHex(
        _bookId + _catalogId + _num + _forceServer, AppConfig.cryptKey,
        iv: AppConfig.cryptIv);
    String url = AppConfig.BASE_UEL + Api.findArticle + param.toString();
    Article article;
    BaseResp res = await HttpManager().request(url).catchError((onError) {
      print("onError $onError");
    });
    if (res == null) {
      return Article.fromJson(
          bookId: bookId.toString(),
          catalogId: catalogId.toString(),
          num: num.toString());
    }
    Map<String, dynamic> jsonObject = jsonDecode(res.data);
    String content = jsonObject['container'];
    var _catalog = jsonObject['catalog'];
    var _nextCatalog = jsonObject['nextCatalog'];
    var _preCatalog = jsonObject['lastCatalog'];
    String nextCatalogId = "";
    String nextCatalogNum = "";
    String preCatalogId = "";
    String preCatalogNum = "";
    if (_nextCatalog != null) {
      nextCatalogId = _nextCatalog['id'].toString();
      nextCatalogNum = _nextCatalog['num'].toString();
    }
    if (_preCatalog != null) {
      preCatalogId = _preCatalog['id'].toString();
      preCatalogNum = _preCatalog['num'].toString();
    }
    article = Article.fromJson(
        bookId: bookId.toString(),
        catalogId: catalogId.toString(),
        name: _catalog['name'].toString(),
        num: num.toString(),
        type: _catalog['type'].toString(),
        updateTime: _catalog['updateTime'].toString(),
        isReptileTool: _catalog['isReptileTool'].toString(),
        reptileAddress: _catalog['reptileAddress'].toString(),
        content: content.toString(),
        nextCatalogId: nextCatalogId.toString(),
        nextCatalogNum: nextCatalogNum.toString(),
        preCatalogId: preCatalogId.toString(),
        preCatalogNum: preCatalogNum.toString());
    return article;
  }
}
